<?php

namespace app\api\controller;

use app\common\controller\Api;
use  app\admin\model\Lun;
use  app\admin\model\Message;
use  app\admin\model\Introduce;
use  app\admin\model\Question;
use  app\admin\model\Image;
use  app\admin\model\Category;
use  app\admin\model\Order;
use Monolog\Handler\IFTTTHandler;
use think\Env;
use  think\Db;
use think\Config;
use app\common\exception\UploadException;
use app\common\library\Upload;

// 声明命名空间
use Obs\ObsClient;
use think\Exception;
use tool\ExcelUtil;

/**
 * 配置
 */
class Home extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $redis;
    private $openid;
    private $user_arr;

    private $appid;
    private $secret;

    public function _initialize()
    {
        parent::_initialize();

        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));

        $this->appid = Env::get('wechat.appid');
        $this->secret = Env::get('wechat.secret');

        $this->openid = empty($_SERVER['HTTP_OPENID']) ? '':$_SERVER['HTTP_OPENID'];//获取openid

        $this->user_arr = Db::table('fa_users')
            ->where('openid',$this->openid)
            ->find();


    }

    /**
     *
     * 首页轮播图接口
     */
    public function lun()
    {

        $list = Db::table('fa_image')
            ->where('status',1)
            ->order(['sort'=>'desc','id'=>'desc'])
            ->select();

        $this->success('查询成功', $list);
    }

    /**
     * 查询轮播图详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function get_lun(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');

        $data = Db::table('fa_image')
            ->where('id',$id)
            ->find();

        $this->success('查询成功', $data);
    }


    /**
     * 获取关注我们二维码
     *
     */
    public function get_us(){
        $images = $this->redis->hGet('humeng:set','images');
        $imagebj = $this->redis->hGet('humeng:set','imagebj');

        $arr = [
            'image' => $images,
            'imagebj' => $imagebj,
        ];


        $this->success('查询成功', $arr);
    }

    /**
     * 关于路印
     *
     */
    public function get_luyin(){
        $image = $this->redis->hGet('humeng:set','image');
        $msg = $this->redis->hGet('humeng:set','msg');
        $phone = $this->redis->hGet('humeng:set','phone');
        $address = $this->redis->hGet('humeng:set','address');
        $longitude = $this->redis->hGet('humeng:set','longitude');
        $latitude = $this->redis->hGet('humeng:set','latitude');

        $row = [
            'image' => $image,
            'msg' => $msg,
            'phone' => $phone,
            'address' => $address,
            'longitude' => $longitude,
            'latitude' => $latitude,
        ];

        $this->success('查询成功', $row);
    }

    /**
     * 健康俱乐部
     *
     */
    public function get_club(){
        $contents = $this->redis->hGet('humeng:set','contents');

        $this->success('查询成功', $contents);
    }

    /**
     * 会员规则
     *
     */
    public function vip_rule(){
        $vip_content = $this->redis->hGet('humeng:set','vip_content');

        $this->success('查询成功', $vip_content);
    }


    /**
     * 路印书院
     *
     */
    public function book_list(){
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 5:request()->get('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $data = Db::table('fa_book')
            ->field('id,image,title,browse_count,give_count,msg')
            ->where('status',1)
            ->order('id','desc')
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_book')
            ->where('status',1)
            ->count();

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);

    }

    /**
     * 路印书院详情
     *
     */
    public function get_book(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');//获取id

        $data =  Db::table('fa_book')
            ->field('id,content,title,create_time')
            ->where('id',$id)
            ->find();


        if (!empty($data)){
            $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
            if (empty($this->user_arr)){
                $data['is_praise'] = 0;
            }else{
                $praise = Db::table('fa_praise')
                    ->where(['user_id'=>$this->user_arr['id'],'book_id'=>$id])
                    ->find();
                $data['is_praise'] = empty($praise)?0:$praise['praise'];
            }
        }


        //浏览量递增
        Db::table('fa_book')
            ->where('id',$id)
            ->setInc('browse_count',1);

        $this->success('查询成功',$data);
    }

    /**
     * 科普视频
     *
     */
    public function movie_list(){
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 5:request()->get('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $data = Db::table('fa_movie')
            ->field('id,image,title,url')
            ->where('status',1)
            ->order(['sort'=>'desc','id'=>'desc'])
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_movie')
            ->where('status',1)
            ->count();

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 获取专家列表
     *
     */
    public function get_medic(){
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 5:request()->get('limt');//获取每页显示条数
        $speciality = empty(request()->get('speciality')) ? '':request()->get('speciality');//获取擅长

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        if (!empty($speciality)){
            $str = explode(',',$speciality);

            if (count($str) == 1){
                $where['speciality'] = ['like','%'.$str[0].'%'];
            }else{
                foreach ($str as $k=>$v){
                    $str_arr[$k] = ['like','%'.$v.'%'];
                }

                $where['speciality'] = [$str_arr,'and'];
            }
        }else{
            $where = [];
        }

        $data = Db::table('fa_medic')
            ->field('id,image,name,type,position,registration_fee,speciality,label')
            ->where(['status'=>1,'type'=>'专家'])
            ->where($where)
            ->order(['sort'=>'desc','id'=>'desc'])
            ->limit($page_start,$limt)
            ->select();


        $total = Db::table('fa_medic')
            ->where(['status'=>1,'type'=>'专家'])
            ->where($where)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                if ($v['label'] == 1){
                    $data[$k]['label'] = '常驻专家';
                }elseif ($v['label'] == 2){
                    $data[$k]['label'] = '首席专家';
                }elseif ($v['label'] == 3){
                    $data[$k]['label'] = '智库专家';
                }else{
                    $data[$k]['label'] = '';
                }

            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 获取咨询项目数据
     *
     */
    public function get_project(){
        $data = Db::table('fa_categorys')
            ->field('id,name')
            ->where('type',1)
            ->select();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['child'] = Db::table('fa_project')
                    ->field('id,project_name')
                    ->where('category_id',$v['id'])
                    ->select();
            }
        }

        $this->success('查询成功',$data);
    }

    /**
     * 获取专家详情
     *
     */
    public function medic_edit(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');//获取id

        $data = Db::table('fa_medic')
            ->field('id,name,image,type,position,registration_fee,speciality,presentation,label')
            ->where(['id'=>$id,'status'=>1])
            ->find();

        if (!empty($data)){
            if ($data['label'] == 1){
                $data['label'] = '常驻专家';
            }elseif ($data['label'] == 2){
                $data['label'] = '首席专家';
            }elseif ($data['label'] == 3){
                $data['label'] = '智库专家';
            }else{
                $data['label'] = '';
            }
        }


        $this->success('查询成功',$data);
    }

    /**
     * 获取预约时间
     *
     */
    public function get_time(){
        $date = empty(request()->get('date')) ? $this->error('date不能为空'):request()->get('date');//获取date
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');//获取id

        $data = Db::table('fa_working')
            ->where(['medic_id'=>$id,'date'=>$date])
            ->order('time','asc')
            ->select();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $pan = Db::table('fa_registration')
                    ->where('working_id',$v['id'])
                    ->find();
                if (!empty($pan)){
                    unset($data[$k]);
                }

                //判断排班时间段是否过期
                switch ($v['time']){
                    case 1:
                        if (date('Y-m-d H:i:s') > $v['date'].' 10:00:00'){
                            unset($data[$k]);
                        }
                        break;
                    case 2:
                        if (date('Y-m-d H:i:s') > $v['date'].' 11:00:00'){
                            unset($data[$k]);
                        }
                        break;
                    case 3:
                        if (date('Y-m-d H:i:s') > $v['date'].' 12:00:00'){
                            unset($data[$k]);
                        }
                        break;
                    case 4:
                        if (date('Y-m-d H:i:s') > $v['date'].' 15:00:00'){
                            unset($data[$k]);
                        }
                        break;
                    case 5:
                        if (date('Y-m-d H:i:s') > $v['date'].' 16:00:00'){
                            unset($data[$k]);
                        }
                        break;
                    case 6:
                        if (date('Y-m-d H:i:s') > $v['date'].' 17:00:00'){
                            unset($data[$k]);
                        }
                        break;
                }
            }
        }

        $data = array_merge($data);
        $this->success('查询成功',$data);

    }

    /**
     * 获取看诊携带报告
     *
     */
    public function get_reports(){
        $ids = empty(request()->get('ids')) ? $this->error('ids不能为空'):request()->get('ids');//获取ids

        $str = explode(',',$ids);

        if (count($str) == 1){
            $where['project_id'] = $str[0];
        }else{
            foreach ($str as $k=>$v){
                $str_arr[$k] = ['eq',$v];
            }


            $where['project_id'] = [$str_arr,'or'];
        }

        $data = Db::table('fa_reports')
            ->where($where)
            ->select();

        $this->success('查询成功',$data);


    }

    /**
     *
     * 获取专家擅长数据
     */
    public function projects(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');

        $arr = Db::table('fa_medic')
            ->where('id',$id)
            ->find();

        if (empty($arr)){
            $this->error('专家不存在');
        }

        $ids = explode(',',$arr['project_id']);

        if (!empty($ids)){
            $data = Db::table('fa_project')
                ->field('id,project_name')
                ->whereIn('id',$ids)
                ->select();
        }

        $this->success('查询成功',$data);
    }


    /**
     * 修改待就诊状态
     *
     */
    public function registration_status(){
        set_time_limit(0);
        $data = Db::table('fa_registration')
            ->where('status','待就诊')
            ->update([
                'status' => '已关闭',
                'update_time' => time(),
            ]);

        $datas = Db::table('fa_registration')
            ->where('status','待支付')
            ->update([
                'status' => '已关闭',
                'update_time' => time(),
            ]);

        $dt = Db::table('fa_orders')
            ->where('status',0)
            ->update([
                'status' => 4,
                'update_time' => time(),
            ]);

//        if (!empty($data)){
//            foreach ($data as $k=>$v){
//                Db::table('fa_registration')
//                    ->where('id',$v['id'])
//                    ->update([
//                        'status' => '已关闭',
//                        'update_time' => time(),
//                    ]);
//            }
//        }

        return $data;
    }

    /**
     * 医护端获取咨询项目
     *
     */
    public function project(){
        $data = Db::table('fa_project')
            ->field('id,project_name')
            ->order('category_id','desc')
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 医护端获取专家列表
     *
     */
    public function medic(){
        $data = Db::table('fa_medic')
            ->field('id,name')
            ->where('type','专家')
            ->order('id','desc')
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 医护端获取排班日期
     *
     */
    public function get_date(){
        $id = empty(request()->get('medic_id')) ? $this->error('medic_id不能为空'):request()->get('medic_id');

        $data = Db::table('fa_working')
            ->field('id,date')
            ->where(['medic_id'=>$id,'date'=>['>=',date('Y-m-d')]])
            ->select();

        $weekname=array('星期一','星期二','星期三','星期四','星期五','星期六','星期日');
        $arr = [];
        $arrs = [];
        if (!empty($data)){
            foreach ($data as $k=>$v){
                $week = date('w',strtotime($v['date']));
                switch ($week){
                    case 0:
                        $date = $v['date'].'('.$weekname[6].')';
                        break;
                    case 1:
                        $date = $v['date'].'('.$weekname[0].')';
                        break;
                    case 2:
                        $date = $v['date'].'('.$weekname[1].')';
                        break;
                    case 3:
                        $date = $v['date'].'('.$weekname[2].')';
                        break;
                    case 4:
                        $date = $v['date'].'('.$weekname[3].')';
                        break;
                    case 5:
                        $date = $v['date'].'('.$weekname[4].')';
                        break;
                    case 6:
                        $date = $v['date'].'('.$weekname[5].')';
                        break;
                }

                if (!in_array($v['date'],$arr)){
                    $arr[] = $v['date'];
                    $arrs[] = [
                        'date' =>$v['date'],
                        'dates' =>$date,
                    ];
                }
                //$data[$k]['dates'] = $date;
            }
        }

        $this->success('查询成功',$arrs);
    }

    /**
     * 医护端获取排班时间
     *
     */
    public function time(){
        $medic_id = empty(request()->get('medic_id')) ? $this->error('medic_id不能为空'):request()->get('medic_id');
        $date = empty(request()->get('date')) ? $this->error('date不能为空'):request()->get('date');

        $data = Db::table('fa_working')
            ->field('id,time')
            ->where(['medic_id'=>$medic_id,'date'=>$date])
            ->select();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $registration = Db::table('fa_registration')
                    ->where('working_id',$v['id'])
                    ->count();
                if ($registration > 0){
                    unset($data[$k]);
                }else{
                    switch ($v['time']){
                        case 1:
                            $time = strtotime($date.' 10:00:00');
                            $data[$k]['times'] = '09:00-10:00';
                            break;
                        case 2:
                            $time = strtotime($date.' 11:00:00');
                            $data[$k]['times'] = '10:00-11:00';
                            break;
                        case 3:
                            $time = strtotime($date.' 12:00:00');
                            $data[$k]['times'] = '11:00-12:00';
                            break;
                        case 4:
                            $time = strtotime($date.' 15:00:00');
                            $data[$k]['times'] = '14:00-15:00';
                            break;
                        case 5:
                            $time = strtotime($date.' 16:00:00');
                            $data[$k]['times'] = '15:00-16:00';
                            break;
                        case 6:
                            $time = strtotime($date.' 17:00:00');
                            $data[$k]['times'] = '16:00-17:00';
                            break;
                    }

                    if (time() > $time){
                        unset($data[$k]);
                    }
                }
            }
            $data = array_merge($data);
        }

        $this->success('查询成功',$data);
    }

    /**
     * 获取看诊项目
     *
     */
    public function get_disease(){
        $data = Db::table('fa_disease')
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 获取项目分类接口
     *
     */
    public function get_classify(){
        $type = empty(request()->get('type')) ? $this->error('type不能为空'):request()->get('type');
        $data = Db::table('fa_categorys')
            ->where('type',$type)
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 获取诊疗项目数据
     *
     */
    public function get_diagnosis(){
        $categorys_id = empty(request()->get('categorys_id')) ? '':request()->get('categorys_id');
        $name = empty(request()->get('name')) ? '':request()->get('name');
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 10:request()->get('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }

        if (empty($categorys_id)){
            $data = Db::table('fa_diagnosis')
                ->where($where)
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_diagnosis')
                ->where($where)
                ->count();

        }else{
            $data = Db::table('fa_diagnosis')
                ->where('categorys_id',$categorys_id)
                ->where($where)
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_diagnosis')
                ->where('categorys_id',$categorys_id)
                ->where($where)
                ->count();
        }

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['counts'] = 1;
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 获取药品列表数据
     *
     */
    public function get_medicine(){
        $status = empty(request()->get('status')) ? '':request()->get('status');
        $type = empty(request()->get('type')) ? '':request()->get('type');
        $name = empty(request()->get('name')) ? '':request()->get('name');
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 10:request()->get('limt');//获取每页显示条数


        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        $wheres = [];
        if (!empty($status)){
            $wheres['b.type'] = ['<>','耗材'];
        }

        if (!empty($type)){
            $where['b.type'] = $type;
            $wheres = [];
        }

        if (!empty($name)){
            $where['b.medicine_name'] = ['like','%'.$name.'%'];
        }

        $data = Db::table('fa_storage')
            ->alias('a')
            ->field('a.id,b.code,b.medicine_name,b.unit,b.specification,b.supplier_name,b.model_number,b.type,b.msg,a.quantity as count,a.sell as sell')
            ->join('fa_medicine b','b.id=a.medicine_id')
            ->where('a.quantity','<>',0)
            ->where('b.is_del',0)
            ->where($where)
            ->where($wheres)
            ->order(['a.end_time'=>'asc','a.id'=>'desc'])
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_storage')
            ->alias('a')
            ->join('fa_medicine b','b.id=a.medicine_id')
            ->where('a.quantity','<>',0)
            ->where('b.is_del',0)
            ->where($where)
            ->where($wheres)
            ->count();


//        if (empty($type)){
//            $data = Db::table('fa_medicine')
//                ->where('count','<>',0)
//                ->limit($page_start,$limt)
//                ->select();
//
//            $total = Db::table('fa_medicine')
//                ->where('count','<>',0)
//                ->count();
//
//        }else{
//            $data = Db::table('fa_medicine')
//                ->where('count','<>',0)
//                ->where('type',$type)
//                ->limit($page_start,$limt)
//                ->select();
//
//            $total = Db::table('fa_medicine')
//                ->where('count','<>',0)
//                ->where('type',$type)
//                ->count();
//        }
//
        if (!empty($data)){
            foreach ($data as $k=>$v){
//                $find = Db::table('fa_storage')
//                    ->where(['medicine_id'=>$v['id'],'quantity'=>['<>',0]])
//                    ->order(['end_time'=>'asc','id'=>'desc'])
//                    ->find();
//                $data[$k]['sell'] = $find['sell'];
                $data[$k]['counts'] = 1;
            }
        }


        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 获取会员服务列表数据
     *
     */
    public function vip_serve(){
        $name = empty(request()->get('name')) ? '':request()->get('name');
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 10:request()->get('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }

            $data = Db::table('fa_vip_serve')
                ->where($where)
                ->limit($page_start,$limt)
                ->select();

            $total = Db::table('fa_vip_serve')
                ->where($where)
                ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['counts'] = 1;
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     * 获取体检项目列表数据
     *
     */
    public function health_serve(){
        $name = empty(request()->get('name')) ? '':request()->get('name');
        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 10:request()->get('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $where = [];
        if (!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }

        $data = Db::table('fa_health')
            ->field('id,name,price,msg')
            ->where($where)
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_health')
            ->where($where)
            ->count();

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);
    }

    /**
     *
     * 获取邀请好友背景图
     */
    public function get_background(){
        $imagess = $this->redis->hGet('humeng:set','imagess');

        $this->success('查询成功',$imagess);
    }


    /**
     * 评分表详情
     *
     */
    public function get_score(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');

        $data = Db::table('fa_score')
            ->where('id',$id)
            ->find();

        if (!empty($data)){
            $data['str'] = json_decode($data['str'],true);
        }

        $this->success('成功',$data);
    }

    /**
     * 获取会员等级
     *
     */
    public function vip_level(){
        $data = Db::table('fa_vip_level')
            ->field('id,level,level_name')
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 待确认药品单-详情
     *
     */
    public function get_confirmed(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');
        $data = Db::table('fa_drug')
            ->where('order_id',$id)
            ->select();


        $this->success('成功',$data);

    }


    /**
     * 修改待缴费诊疗订单状态
     *
     */
    public function order_status(){
        var_dump('废弃');die();
        set_time_limit(0);
        $data = Db::table('fa_diagnosis_order')
            ->where('status',0)
            ->update([
                'status' => 3,
                'update_time' => time(),
            ]);


        return $data;
    }

    /**
     * 6+1详情
     *
     */
    public function get_seven(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');

        $data = Db::table('fa_seven')
            ->field('id,title,content')
            ->where('id',$id)
            ->find();

        $this->success('成功',$data);
    }

    /**
     * 通过手机号获取用户数据
     *
     */
    public function phone_user(){
        $phone = empty(request()->get('phone')) ? $this->error('phone不能为空'):request()->get('phone');

        $data = Db::table('fa_users')
            ->field('id,nickname,phone')
            ->where('phone',$phone)
            ->select();

        if (empty($data)){
            $this->error('数据为空',[]);
        }

        $this->success('成功',$data);
    }


    /**
     * 场所/商品列表数据
     *
     */
    public function products_list(){
        $type = empty(request()->get('type')) ? $this->error('type不能为空'):request()->get('type');

        $page = empty(request()->get('page')) ? 1:request()->get('page');//获取页码
        $limt = empty(request()->get('limt')) ? 10:request()->get('limt');//获取每页显示条数

        //分页
        if ($page == 1) {
            $page_start = 0;
            $page_end = $limt-1;
        } else {
            $page_start = ($page - 1) * $limt;
            $page_end = $page_start + $limt-1;
        }

        $data = Db::table('fa_products')
            ->field('id,type,name,price,image,create_time')
            ->where('type',$type)
            ->limit($page_start,$limt)
            ->select();

        $total = Db::table('fa_products')
            ->where('type',$type)
            ->count();

        if (!empty($data)){
            foreach ($data as $k=>$v){
                $data[$k]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            }
        }

        //组装数据
        $datas = [
            'page' => $page,
            'total' => $total,
            'limt' => $limt,
            'list' => $data,
        ];

        $this->success('查询成功',$datas);

    }

    /**
     * 场所/商品详情
     *
     */
    public function get_products(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');

        $data = Db::table('fa_products')
            ->where('id',$id)
            ->find();

        if (!empty($data)){
            $data['create_time'] = date('Y-m-d H:i:s',$data['create_time']);
            switch ($data['opening_hours']){
                case 1:
                    $data['opening_hours'] = '每周一';
                    break;
                case 2:
                    $data['opening_hours'] = '每周二';
                    break;
                case 3:
                    $data['opening_hours'] = '每周三';
                    break;
                case 4:
                    $data['opening_hours'] = '每周四';
                    break;
                case 5:
                    $data['opening_hours'] = '每周五';
                    break;
                case 6:
                    $data['opening_hours'] = '每周六';
                    break;
                case 7:
                    $data['opening_hours'] = '每周日';
                    break;
                case 8:
                    $data['opening_hours'] = '周一至周日';
                    break;
            }
        }

        $this->success('查询成功',$data);
    }

    /**
     * 会员卡等级
     *
     */
    public function get_card(){
        $data = Db::table('fa_vip_card')
            ->field('id,name')
            ->select();

        $this->success('查询成功',$data);

    }

    /**
     * 获取审批人
     *
     */
    public function examin_list(){
        $id = empty(request()->get('id')) ? $this->error('id不能为空'):request()->get('id');

        $data = Db::table('fa_oa_examine')
            ->alias('a')
            ->field('a.id,a.admin_id,b.nickname,b.avatar,a.type')
            ->join('fa_admin b','a.admin_id=b.id','left')
            ->where('a.oa_id',$id)
            ->order('a.type','asc')
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 部门列表
     *
     */
    public function get_group(){
        $data = Db::table('fa_auth_group')
            ->field('id,name')
            ->where('pid',1)
            ->select();

        $this->success('查询成功',$data);
    }

    /**
     * 获取就诊人数据
     *
     */
    public function get_info(){
        $number = empty(request()->get('number')) ? $this->error('number不能为空'):request()->get('number');

        $data = Db::table('fa_info')
            ->field('id,name')
            ->where('number',$number)
            ->find();

        if (empty($data)){
            $this->error('查询失败');
        }else{
            $this->success('查询成功',$data);
        }

    }

    /**
     *
     * 6+1服务列表
     */
    public function seven_list(){
        $data = Db::table('fa_seven')
            ->field('id,title,image,msg')
            ->select();

        $this->success('查询成功',$data);
    }


    /**
     * 获取分享码
     *
     */
    public function get_qrcode(){
        require '../vendor/obs/obs-autoloader.php';
        $pid = empty(request()->get('did')) ? $this->error('did不能为空',[]):request()->get('did');
        //$str = '{"scene":"pid='.$pid.'"}';//测试
        //$str = '{"scene":"pid='.$pid.'","page":"pages/login/login"}';
        //$str = '{"scene":"'.$pid.'","page":"pages/login/login"}';
        //$str = urlencode('pid='.$pid);
        $str = '{"scene":"did.'.$pid.'","page":"pages/login/login"}';

        $appid = $this->appid;
        $secret = $this->secret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;

        $access_toke = $this->redis->Get('access_toke');//设置redis

        if ($access_toke == false){
            $result = file_get_contents($url);
            $result = json_decode($result,true);

            if (isset($result['errcode'])){
                $this->error('token获取失败',$result);
            }
            //将access_toke存redis
            $this->redis->Set('access_toke',$result['access_token'],7000);//设置redis
            $access_toke = $result['access_token'];
        }

        //header('Content-type: image/jpeg');
        $urls = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_toke;

        $result = http($urls,$str,'POST',[],true);

        $results = json_decode($result,true);


        if (isset($results['errcode'])){
            if ($results['errcode'] == 40001){
                $result = file_get_contents($url);
                $result = json_decode($result,true);

                if (isset($result['errcode'])){
                    $this->error('token获取失败',$result);
                }
                //将access_toke存redis
                $this->redis->Set('access_toke',$result['access_token'],7000);//设置redis
                $access_toke = $result['access_token'];

                $urls = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_toke;

                $result = http($urls,$str,'POST',[],true);
            }else{
                return $result;
            }

        }


        //var_dump($result);die();
        $name = time() . uniqid() . '.jpg'; //临时文件名称

        $dir_path = "./log/logs";
        if (!file_exists($dir_path)){
            mkdir($dir_path,755,1);
        }
        $path = $dir_path . '/' . $name;

        if (file_put_contents($path, $result)){
            //开始obs上传,引入文件
            // 创建ObsClient实例
            $obsClient = new ObsClient([
                'key' => 'W2O4GDBTRQIFRODHXVDU',
                'secret' => '8jpkOkdEFdgZh53DzZnCkIrHczPfIWc8RVK1p9iQ',
                'endpoint' => 'https://obs.cn-south-1.myhuaweicloud.com'
            ]);

            try {

                $resp = $obsClient->putObject([
                    'Bucket' => 'obs-c95m',
                    'Key' => 'luyin/'.$name,
                    //'SourceFile' => $f_path  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                    'SourceFile' => $path  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                ]);
                unlink($path); //上传本地临时文件

                $img_name =  'https://img.looin.cn/luyin/'.$name;

                $ar = [
                    'img_name' => $img_name,
                ];

                $this->success('成功',$ar);


            } catch (\Obs\ObsException $obsException){
                $this->error($obsException->getExceptionCode(),$obsException->getExceptionMessage());
            }
        }
    }


    /**
     * 上传
     *
     */
    public function uploading(){
        var_dump(123);die();
        require '../vendor/obs/obs-autoloader.php';

        //$namess = empty(request()->post('name')) ? '':request()->post('name');
        $namess = request()->post('name');
        $file = $_FILES['file'];


        //var_dump($file);die();
        //获取表单上传文件
        if ($file) {
            $tmpPname = $file['name'];//客户端文件的原名称
            $tmpP = $file['tmp_name'];//文件被上传后在服务端储存的临时文件名
            if ($tmpP) {
                //获取文件后缀
                $suffix = pathinfo($tmpPname, PATHINFO_EXTENSION);
//                $filetype = ['jpg', 'jpeg', 'gif', 'bmp', 'png','mp3','mp4','pdf'];
//                if (!in_array($suffix, $filetype)) {
//                    $this->error('格式不正确');
//                }

//                $dir_path = "./log/logs";
//                if (!file_exists($dir_path)){
//                    mkdir($dir_path,755,1);
//                }

                $name = time() . uniqid() . '.' . $suffix; //临时文件名称

                //$f_path = $dir_path . '/' . $name; //临时文件路劲


                //if (move_uploaded_file($tmpP, $f_path)) {
                //开始obs上传,引入文件
                // 创建ObsClient实例
                $obsClient = new ObsClient([
                    'key' => 'W2O4GDBTRQIFRODHXVDU',
                    'secret' => '8jpkOkdEFdgZh53DzZnCkIrHczPfIWc8RVK1p9iQ',
                    'endpoint' => 'https://obs.cn-south-1.myhuaweicloud.com'
                ]);

                try {

                    $resp = $obsClient->putObject([
                        'Bucket' => 'obs-c95m',
                        'Key' => 'luyin/'.$name,
                        //'SourceFile' => $f_path  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                        'SourceFile' => $tmpP,  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                        // 设置SSE-C算法加密对象
                        'SseC' => 'AES256',
                        'SseCKey' => '0pVVwcpV3q6X84tugiUmYxIXyYiHPjV6'

                    ]);
                    //unlink($f_path); //上传本地临时文件

                    $img_name =  'https://img.looin.cn/luyin/'.$name;
                    if (!empty($namess)){
                        $ar = [
                            'img_name' => $img_name,
                            'name' => $namess,
                            'suffix' => $suffix,
                        ];
                    }else{
                        $ar = [
                            'img_name' => $img_name,
                            'name' => $namess,
                            'suffix' => $suffix,
                        ];
                    }
                    $this->success('成功',$ar);


                } catch (\Obs\ObsException $obsException){
                    $this->error($obsException->getExceptionCode(),$obsException->getExceptionMessage());
                }


                //}

            }
        }



    }

    public function download(){
        // 引入依赖库
        require '../vendor/obs/obs-autoloader.php';
        // 使用源码安装时引入SDK代码库
        // require 'obs-autoloader.php';

        // 创建ObsClient实例
        $obsClient = new ObsClient([
            'key' => 'W2O4GDBTRQIFRODHXVDU',
            'secret' => '8jpkOkdEFdgZh53DzZnCkIrHczPfIWc8RVK1p9iQ',
            'endpoint' => 'https://obs.cn-south-1.myhuaweicloud.com'
        ]);

        $resp = $obsClient->getObject ( [
            'Bucket' => 'obs-c95m',
            'Key' => 'luyin/1629107671611a35d7e5e55.jpg',
            // 设置SSE-C算法解密对象
            'SseC' => 'AES256',
            // 此处的密钥必须和上传对象加密时使用的密钥一致
            'SseCKey' => '0pVVwcpV3q6X84tugiUmYxIXyYiHPjV6'
        ] );
        printf ( "RequestId:%s\n", $resp ['RequestId'] );
        printf("Object Content:\n");
        // 获取对象内容
        //echo $resp ['Body'];

        $img=base64_encode($resp ['Body']);

        echo '<img src="data:image/jpeg;base64,'.$img.'"/>';

    }

    /**
     *
     * 过期vip处理
     */
    public function del_vip(){
        set_time_limit(0);
        $vip = Db::table('fa_users')
            ->where('vip_time','<',date('Y-m-d'))
            ->order('vip_time','desc')
            ->limit(5000)
            ->select();

        if (!empty($vip)){
            foreach ($vip as $k=>$v){
                $update = Db::table('fa_users')
                    ->where('id',$v['id'])
                    ->update([
                        'level' => 1,
                        'pid' => 0,
                        'count' => 1,
                        'vip_time' => NULL,
                        'update_time' => time(),
                    ]);

                Db::table('fa_deduction')
                    ->where('user_id',$v['id'])
                    ->delete();

                Db::table('fa_info')
                    ->where('binding',$v['id'])
                    ->update([
                        'binding' => 0,
                        'update_time' => time(),
                    ]);
            }

        }

        return 1;
    }

    /**
     * 验证器
     *
     */
    public function check(){
        try{
            $data = [
                'id' => request()->get('id'),
            ];
            //$result = $this->validate($data,'Check.check');
            $result = $this->validate($data,'Check.check');
            if(true !== $result){
                // 验证失败 输出错误信息
                $this->error($result);
            }
            //验证数据
//        $validate = \think\Loader::validate('Check');
//        if(!$validate->scene('check')->check($data)){
//            $this->error($validate->getError());die;
//        }

            var_dump($data);die();
        }catch (Exception $e){
            throw new Exception($e->getMessage());
        }

    }


    /**
     * 测试代码
     *
     */
    public function ceshi(){
        $a = Db::table('fa_treatment')
            ->alias('a')
            ->field('a.*,b.info_id')
            ->join('fa_diagnosis_order b','a.order_id=b.id')
            ->select();

//        foreach ($a as $k=>$v){
//            Db::table('fa_treatment')
//                ->where('id',$v['id'])
//                ->update([
//                    'info_id' => $v['info_id'],
//                ]);
//        }


        var_dump($a);die();
        return $a;


    }
}
